package com.ecarx.module_log;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.ecarx.library_base.base_fragment.BaseFragment;
import com.ecarx.library_base.base_util.NotifyListener;
import com.ecarx.library_base.base_util.SPUtil;
import com.ecarx.module_log.bean.FileBean;
import com.ecarx.module_log.controller.RecordLimitController;

import java.util.Arrays;
import java.util.List;


public class LogScreenCaptureFragment extends BaseFragment {
    private Button mBtnRecordStop, mBtnRecordStart;
    private Spinner mSpinnerTime, mSpinnerNum;
    private TextView mTvRecordStatus;
    private String[] mTimeArray = {"60"};
    private String[] mNumArray = {"60", "120", "0"};
    private static final String SCREEN_RECORD_TIME = "service.screen.record.time";
    private static final String SCREEN_RECORD_NUM = "service.screen.record.num";

    private String mMaxnum;
    private String mMaxTime;
    private RecordLimitController mRecordLimitController;
    private ScreenCaptureOutFragment mOutFragment;


    public LogScreenCaptureFragment() {
        // Required empty public constructor
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_log_screen;
    }

    @Override
    protected void init(View view) {
        findView(view);
        checkRecording(false);
        initData();
        initListener();


    }

    private void initData() {
        mRecordLimitController = new RecordLimitController();

        ArrayAdapter<String> timeAdapter = getStringArrayAdapter(Arrays.asList(getResources().getStringArray(R.array.screen_record_time)));
        mSpinnerTime.post(() -> mSpinnerTime.setDropDownVerticalOffset(mSpinnerTime.getHeight()));
        mSpinnerTime.setAdapter(timeAdapter);
        ArrayAdapter<String> numAdapter = getStringArrayAdapter(Arrays.asList(getResources().getStringArray(R.array.screen_record_num)));
        mSpinnerNum.post(() -> mSpinnerNum.setDropDownVerticalOffset(mSpinnerNum.getHeight()));
        mSpinnerNum.setAdapter(numAdapter);
        mMaxTime = (String) SPUtil.get(getActivity(), SCREEN_RECORD_TIME, "60");
        mMaxnum = (String) SPUtil.get(getActivity(), SCREEN_RECORD_NUM, "60");
        int selectTime = getSpinnerSelect(mMaxTime, mTimeArray);
        mSpinnerTime.setSelection(selectTime);
        int selectNum = getSpinnerSelect(mMaxnum, mNumArray);
        mSpinnerNum.setSelection(selectNum);
    }

    private int getSpinnerSelect(String recordTime, String[] array) {
        int select = 0;
        for (int i = 0; i < array.length; i++) {
            if (recordTime.equals(array[i])) {
                select = i;
                break;
            }
        }
        return select;
    }

    private ArrayAdapter<String> getStringArrayAdapter(List<String> list) {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, list);
        adapter.setDropDownViewResource(R.layout.item_main_spinner);
        return adapter;
    }

    private void findView(View view) {
        mBtnRecordStop = view.findViewById(R.id.btn_record_stop);
        mBtnRecordStart = view.findViewById(R.id.btn_record_start);
        mSpinnerTime = view.findViewById(R.id.spinner_time);
        mSpinnerNum = view.findViewById(R.id.spinner_num);
        mTvRecordStatus = view.findViewById(R.id.tv_record_status);
        mOutFragment = (ScreenCaptureOutFragment) getChildFragmentManager().findFragmentById(R.id.fragment_out);
    }

    private void initListener() {
        mBtnRecordStart.setOnClickListener(v -> {
            checkRecording(true);
            mRecordLimitController.startRecord(mMaxTime, mMaxnum, new RecordLimitController.LimitListener() {

                @Override
                public void deleteFileList(List<String> fileName) {
                    mOutFragment.fileDelete(1, fileName);
                }

                @Override
                public void recordError(String errMsg) {
                    showToast(errMsg);
                    checkRecording(false);
                }

                @Override
                public void fileAdd(List<FileBean> fileBeans) {
                    mOutFragment.fileAdd(1, fileBeans);
                }

                @Override
                public void startOverMax() {
                    checkRecording(false);
                    showToast(getString(R.string.no_space_record));
                }

            });
        });
        mBtnRecordStop.setOnClickListener(v -> {
            checkRecording(false);
            mRecordLimitController.clickStop();
            mOutFragment.fileAdd(1, mRecordLimitController.getRecordFile());
            mRecordLimitController.clearShowFile();
        });
        setSpinnerLisenter(mSpinnerTime, (result, data) -> {
            mMaxTime = mTimeArray[(int) result];
            SPUtil.put(getActivity(), SCREEN_RECORD_TIME, mMaxTime);
        });
        setSpinnerLisenter(mSpinnerNum, (result, data) -> {
            mMaxnum = mNumArray[(int) result];
            SPUtil.put(getActivity(), SCREEN_RECORD_NUM, mMaxnum);
        });

    }


    private void checkRecording(boolean isRecording) {
        mOutFragment.setRecording(isRecording);
        mBtnRecordStart.setEnabled(!isRecording);
        if (isRecording) {
            mBtnRecordStop.setEnabled(false);
            mBtnRecordStop.postDelayed(() -> {
                if (mRecordLimitController.isRecording()) {
                    mBtnRecordStop.setEnabled(true);
                }
            }, 1000);
            changeRecordStatus(R.string.opened, R.mipmap.success, R.color.E7FFE9, isRecording);
        } else {
            changeRecordStatus(R.string.stoped, R.mipmap.error, R.color.FFECE7, isRecording);
            mBtnRecordStop.setEnabled(isRecording);
        }
        mSpinnerNum.setEnabled(!isRecording);
        mSpinnerTime.setEnabled(!isRecording);
    }

    private void setSpinnerLisenter(Spinner spinner, NotifyListener listener) {
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                listener.onNotify(position, position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 设置记录状态
     */
    private void changeRecordStatus(int resString, int resMipmap, int resColor, boolean isRecording) {
        mTvRecordStatus.setText(resString);
        mTvRecordStatus.setSelected(isRecording);
        mTvRecordStatus.setCompoundDrawablePadding(0);
        mTvRecordStatus.setCompoundDrawablesWithIntrinsicBounds(ActivityCompat.getDrawable(getActivity(), resMipmap), null, null, null);
        mTvRecordStatus.setBackgroundColor(ActivityCompat.getColor(getActivity(), resColor));
    }


}